package com.iot08.push.mqtt.conf;

import com.iot08.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;

import java.util.Map;

/**
 * @version 1.0
 * @Description: MQTT消费者配置
 * @author: Rock
 * @time: 2020/9/21 19:10
 */
@Slf4j
@Configuration
public class MqttConfig {

    /**
     * 入站通道名（消费者）
     */
    public static final String CHANNEL_NAME_IN = "mqttInboundChannel";
    /**
     * 出站通道名（生产者）
     */
    public static final String CHANNEL_NAME_OUT = "mqttOutboundChannel";
    public static final String FACTORY_NAME = "mqttPahoClientFactory";
    public static final String OPTIONS_NAME = "mqttConnectOptions";

    @Value("${mqtt.username}")
    private String username;

    @Value("${mqtt.password}")
    private String password;

    @Value("#{'${mqtt.url}'.split(',')}")
    private String[] urls;

    @Value("${mqtt.keep-alive-inflight}")
    private Integer keepAlive;

    /**
     * 消费者clientId前缀（消费者）
     */
    @Value("${mqtt.consumer.client-id-prefix}")
    private String consumerClientIdPrefix;

    /**
     * 消费者订阅主题（消费者）
     */
    @Value("#{'${mqtt.consumer.topic}'.split(',')}")
    private String[] consumerTopic;

    /**
     * 消费者订阅主题设置服务质量（消费者）
     */
    @Value("#{'${mqtt.consumer.qos}'.split(',')}")
    private int[] consumerQos;

    /**
     * 消费者操作完成的超时时长（消费者）
     */
    @Value("${mqtt.consumer.completion-timeout}")
    private long completionTimeout;

    /**
     * 生产者clientId前缀（生产者）
     */
    @Value("${mqtt.producer.client-id-prefix}")
    private String producerClientIdPrefix;

    /**
     * 发送消息的默认topic（生产者）
     */
    //@Value("${mqtt.producer.topic}")
    //private String producerDefaultTopic;

    @Value("${mqtt.max-inflight}")
    private Integer maxInflight;

    @Value("${mqtt.connection-timeout}")
    private Integer connectionTimeout;

    /**
     * MQTT连接器选项
     *
     * @time: 2020/9/25 10:06
     * @author: Rock
     * @version 1.0
     */
    @Bean(name = OPTIONS_NAME)
    public MqttConnectOptions mqttConnectOptions() {
        MqttConnectOptions options = new MqttConnectOptions();
        // 设置连接的用户名
        options.setUserName(username);
        // 设置连接的密码
        options.setPassword(password.toCharArray());
        options.setServerURIs(urls);
        // 设置会话心跳时间，默认60秒。服务器会每隔（1.5 * KeepAlive）秒的时间向客户端发送心跳判断客户端是否在线，但这个方法并没有重连的机制
        options.setKeepAliveInterval(keepAlive);
        // 设置是否清空session，false表示服务器会保留客户端的连接记录，true表示每次连接到服务器都以新的身份连接
        options.setCleanSession(true);
        // 允许同时发送的消息数量，默认10
        options.setMaxInflight(maxInflight);
        // 设置超时时间，默认30秒
        options.setConnectionTimeout(connectionTimeout);
        // 自动重连
        options.setAutomaticReconnect(true);
        return options;
    }

    /**
     * MQTT客户端
     *
     * @param options
     * @time: 2020/9/25 10:15
     * @author: Rock
     * @version 1.0
     */
    @Bean(name = FACTORY_NAME)
    public MqttPahoClientFactory mqttPahoClientFactory(@Qualifier(OPTIONS_NAME) MqttConnectOptions options) {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(options);
        return factory;
    }

    /**
     * MQTT消费端订阅通道（消息入站）
     *
     * @param
     * @time: 2020/9/25 10:15
     * @author: Rock
     * @version 1.0
     */
    @Bean(name = CHANNEL_NAME_IN)
    public MessageChannel inboundChannel() {
        return new DirectChannel();
    }


    /**
     * MQTT消费端连接配置（消息入站）
     *
     * @param channel
     * @param factory
     * @time: 2020/9/25 10:16
     * @author: Rock
     * @version 1.0
     */
    @Bean
    public MessageProducer inbound(@Qualifier(CHANNEL_NAME_IN) MessageChannel channel,
                                   @Qualifier(FACTORY_NAME) MqttPahoClientFactory factory) {
        // 可以同时消费（订阅）多个Topic
        String clientId = consumerClientIdPrefix + StringUtil.getUuid();
        log.info(" inbound clientId = {} ", clientId);
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(clientId, factory, consumerTopic);
        // 设置操作完成的超时时长，默认30000毫秒
        adapter.setCompletionTimeout(completionTimeout);
        // 配置默认消息转换器(qos=0, retain=false, charset=UTF-8)
        adapter.setConverter(new DefaultPahoMessageConverter());
        // 0 至多一次，数据可能丢失
        // 1 至少一次，数据可能重复
        // 2 只有一次，且仅有一次，最耗性能
        adapter.setQos(consumerQos);
        // 设置订阅通道
        adapter.setOutputChannel(channel);
        return adapter;
    }

    /*************------------- 下面是生产者的配置 -------------*********/

    /**
     * MQTT生产端发布通道（消息出站）
     *
     * @time: 2020/9/25 10:18
     * @author: Rock
     * @version 1.0
     */
    @Bean(name = CHANNEL_NAME_OUT)
    public MessageChannel outboundChannel() {
        return new DirectChannel();
    }

    /**
     * MQTT生产端发布处理器（消息出站）
     *
     * @param factory
     * @time: 2020/9/25 10:19
     * @author: Rock
     * @version 1.0
     */
    @Bean
    @ServiceActivator(inputChannel = CHANNEL_NAME_OUT)
    public MessageHandler outboundHandler(@Qualifier(FACTORY_NAME) MqttPahoClientFactory factory) {
        String clientId = producerClientIdPrefix + StringUtil.getUuid();
        log.info(" outboundHandler clientId = {} ", clientId);
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(clientId, factory);
        messageHandler.setAsync(true);
        messageHandler.setDefaultRetained(false);
        //messageHandler.setDefaultTopic(producerDefaultTopic);
        return messageHandler;
    }

}
